package com.cnswhy.cloud.common.redis.configure;

import com.cnswhy.cloud.common.redis.properties.CnswhyLettuceRedisProperties;
import com.cnswhy.cloud.common.redis.service.IdGeneratorService;
import com.cnswhy.cloud.common.redis.service.RedisService;
import com.cnswhy.cloud.common.redis.utils.RedisObjectSerializer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;


/**
 * Lettuce Redis配置
 *
 * @author cnswhy
 */
@ConditionalOnClass(RedisConnectionFactory.class)
@EnableConfigurationProperties(CnswhyLettuceRedisProperties.class)
@ConditionalOnProperty(prefix =  CnswhyLettuceRedisProperties.PREFIX , name = "enable", havingValue = "true", matchIfMissing = true)
public class CnswhyLettuceRedisConfigure {

    @Bean(name = "redisTemplate")
    @ConditionalOnClass(RedisOperations.class)
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);

        /*Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.activateDefaultTyping(mapper.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(mapper);*/
        RedisObjectSerializer redisObjectSerializer = new RedisObjectSerializer();

        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        template.setKeySerializer(stringRedisSerializer);
        template.setHashKeySerializer(stringRedisSerializer);
        template.setHashValueSerializer(redisObjectSerializer);
        template.setValueSerializer(redisObjectSerializer);
        template.afterPropertiesSet();

        return template;
    }

    @Bean
    @ConditionalOnBean(name = "redisTemplate")
    public RedisService redisService() {
        return new RedisService();
    }
    @Bean
    @ConditionalOnBean(name = "redisTemplate")
    public IdGeneratorService idGeneratorService() {
        return new IdGeneratorService();
    }

}